package providers

import (
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
)

var GinEngine *gin.Engine

/**
 * 初始化框架对象
 */
func init() {
	GinEngine = gin.New()
	ginOpenSession()
}

/**
 * 开启 session
 */
func ginOpenSession() {
	// 是否开启 session
	if !Config.GetBool("app.open_session") {
		return
	}

	//开启session --- start
	//store := cookie.NewStore([]byte("secret"))
	redisConfig := Config.GetStringMap("redis")
	sessionConfig := Config.GetStringMap("session")
	store, err := redis.NewStore(
		10,
		"tcp",
		redisConfig["host"].(string),
		redisConfig["password"].(string),
		[]byte("secret"),
	)
	if err != nil {
		panic("新建 redis 有误:" + err.Error())
	}
	err = redis.SetKeyPrefix(
		store,
		sessionConfig["prefix"].(string),
	)
	if err != nil {
		panic("redis 设置前缀有误:" + err.Error())
	}

	maxAge := int64(time.Hour.Seconds()) * sessionConfig["max_age"].(int64)
	store.Options(sessions.Options{
		MaxAge: int(maxAge),
		Path:   "/",
	})
	GinEngine.Use(sessions.Sessions("mysession", store))
	// 所有的序列化都放在 ApiCmd 中，放在这里会出现重复引入
	//开启session --- end
}
